import { _decorator, Color, Component, instantiate, Label, Node, Prefab, resources, Sprite, SpriteFrame, tween, Vec3, view } from 'cc';
import { CardData } from './CardData';
import { Player } from '../Player';
import { PokerCard } from './PokerCard';
import { AIManager } from './AIManager';
const { ccclass, property } = _decorator;

@ccclass('PockerGameManager')
export class PockerGameManager extends Component {
    @property(Node) deckPosition: Node = null!;
    @property(Prefab) cardPrefab: Prefab = null!;
    @property(Player) players: Player[] = [];

    @property(Prefab)
    gameStartTipPrefab: Prefab = null!;
    
    @property(Prefab)
    okPrefab: Prefab = null!;
    
    @property(Prefab)
    teamSelectBtnPrefab: Prefab = null!;
    
    @property(Node)
    bottomPlayerNode: Node = null!;

    private allCards: CardData[] = [];

    @property(Node)
    remainCountNode: Node = null!; // 新增父节点引用
    @property(Label) remainCountLabel: Label = null!;
    // 存储所有倒计时引用
    private countdownTimers = new Map<string, number>();

    private lastSelectedCard: Node = null!;
    

    async onLoad() {
        this.countdownTimers = new Map();
        await this.preloadResources();
        this.initGame();
    }

    public onCardSelected(card: Node) {
        if (this.lastSelectedCard && this.lastSelectedCard !== card) {
            this.lastSelectedCard.getComponent(PokerCard)?.resetState();
        }
        this.lastSelectedCard = card;
    }

    private async preloadResources() {
        await Promise.all([
            this.preloadCardTextures(),
            this.preloadBackTexture()
        ]);
    }

    private async preloadCardTextures() {
        const loadPromises = [];
        for (let value = 3; value <= 15; value++) {
            for (let suit = 1; suit <= 4; suit++) {
                loadPromises.push(new Promise((resolve) => {
                    resources.load(`textures/pock/pocker/${value}_${suit}/spriteFrame`, 
                        SpriteFrame, () => resolve(true));
                }));
            }
        }
        await Promise.all(loadPromises);
    }

    private async preloadBackTexture() {
        await new Promise((resolve) => {
            resources.load('textures/pock/pocker/1_1/spriteFrame', 
                SpriteFrame, () => resolve(true));
        });
    }

    private async initGame() {
        this.initPlayers();
        this.initAllCountdowns()
        this.scheduleOnce(() => {
            this.generateDeck();
            this.shuffleCards();
            this.dealCards();
            this.findFirstPlayer();
        }, 6);
    }

    // 初始化所有玩家倒计时
    private initAllCountdowns() {
        this.players.forEach(player => {
            // 重置显示
            this.updateCountdownDisplay(player, 30);
            
            // 3秒后开始倒计时（根据需求调整延迟）
            this.scheduleOnce(() => {
                this.startIndividualCountdown(player);
            }, 3);
        });
    }

    private generateDeck() {
        this.allCards = [];
        for (let value = 3; value <= 15; value++) {
            for (let suit = 1; suit <= 4; suit++) {
                this.allCards.push(new CardData(value, suit));
            }
        }
    }

    private shuffleCards() {
        for (let i = this.allCards.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.allCards[i], this.allCards[j]] = [this.allCards[j], this.allCards[i]];
        }
    }

    private async dealCards() {
        const total = this.allCards.length;
        this.remainCountLabel.string = `${total}`;

        for (let i = 0; i < total; i++) {
            const playerIndex = i % 4;
            const currentPlayer = this.players[playerIndex];
            const cardData = this.allCards[i];
            
            this.updateRemainCount(total - i - 1);

            if (currentPlayer?.isBottomPlayer) {
                await this.createPlayerCard(cardData, currentPlayer);
            }
            
            currentPlayer?.addCard(cardData);
        }

        // 发牌完成后
        this.scheduleOnce(() => {
            this.showGameStartTip();
            this.handleSpade7Owner();
        }, 2);
    }

    private showGameStartTip() {
        const tipNode = instantiate(this.gameStartTipPrefab);
        this.deckPosition.addChild(tipNode);
        
        tween(tipNode)
            .delay(2)
            .to(0.5, { opacity: 0 })
            .call(() => tipNode.destroy())
            .start();
    }

    private async createPlayerCard(cardData: CardData, player: Player) {

        try {
            if (!this.cardPrefab.data) {
                throw new Error("Card prefab data is invalid");
            }
    
            const cardNode = instantiate(this.cardPrefab);
            if (!cardNode.isValid) {
                throw new Error("Instantiate card failed");
            }
    
            // 延迟添加到场景树
            this.scheduleOnce(() => {
                this.deckPosition.addChild(cardNode);
            }, 0);
            
            // ...后续逻辑...
        const cardComp = cardNode.getComponent(PokerCard);
        
        if (!cardComp) {
            cardNode.destroy();
            throw new Error("PokerCard component missing!");
        }

        cardComp.init(cardData, false);
        this.deckPosition.addChild(cardNode);
        
        await this.playDealAnimation(cardNode, player.handArea);
        cardComp.flipCard();
        } catch (err) {
            console.error("Create card failed:", err);
        }

        
    }

    private async playDealAnimation(cardNode: Node, target: Node) {
        return new Promise<void>((resolve) => {
            tween(cardNode)
                .to(0.4, { // 发牌速度
                    position: target.position,
                    scale: new Vec3(1, 1, 1),
                    // angle: Math.random() * 30 - 15
                }, { easing: 'sineOut' })
                .call(() => {
                    target.addChild(cardNode);
                    resolve();
                })
                .start();
        });
    }

    private findFirstPlayer() {
        const spade7 = this.allCards.find(c => 
            c.value === 7 && c.suit === 1
        );
        
        const firstPlayer = this.players.find(p =>
            p.cards.some(c => c === spade7)
        );
        
        console.log("First player:", firstPlayer?.node.name);
    }

    private updateRemainCount(count: number) {
        this.remainCountLabel.string = `${count}`;
        this.remainCountNode.active = count > 0;
    }

    // new
    
    private async initPlayers() {
        const chineseNames = await this.loadChineseNames();
        
        this.players.forEach((player, index) => {
            if (!player.isBottomPlayer) {
                // 显示待加入状态
                const waitAdd = player.node.getChildByPath('WaitAdd')?.getComponent(Label);
                const userInfo = player.node.getChildByPath('UserInfo');
                
                if (waitAdd){
                    waitAdd.node.active = true;
                    waitAdd.string = '待加入'
                };
                
                // 3秒后初始化玩家
                this.scheduleOnce(() => {
                    this.initRandomPlayer(player, chineseNames);
                    waitAdd.node.active = false;
                    userInfo.active = true;
                }, 3 + index * 0.5);
            }
            if (player.isBottomPlayer) {
                const btns = player.node.getChildByPath('ActionButtons');
                btns.active = false;
            }
        });
    }
    
    private async initRandomPlayer(player: Player, names: string[]) {
        // 随机生成玩家信息
        const userInfo = player.node.getChildByPath('UserInfo');
        if (!userInfo) return;
        
    
        // 随机名字
        const nickName = userInfo.getChildByPath('Nickname')?.getComponent(Label);
        if (nickName) nickName.string = names[Math.floor(Math.random() * names.length)];
    
        // 随机头像
        const avatar = userInfo.getChildByPath('Avatar')?.getComponent(Sprite);
        if (avatar) {
            const gender = Math.random() > 0.5 ? 'm' : 'w';
            resources.load(`textures/icon/avatar_${gender}/spriteFrame`, SpriteFrame, (err, frame) => {
                if (frame) avatar.spriteFrame = frame;
            });
        }
    
        // 随机金币
        const chipCount = userInfo.getChildByPath('ChipCount/ChipCount')?.getComponent(Label);
        if (chipCount) {
            chipCount.string = Math.floor(3000 + Math.random() * 7000).toString();
        }

        const teamLabel = player.node.getChildByPath('UserInfo/IsTeam')?.getComponent(Label);
    if (teamLabel) {
        teamLabel.node.active = false; // 默认隐藏
    }
    
        // 标记准备状态
        this.scheduleOnce(() => {
            this.showReadyState(player);
        }, 1);
    }
    
    private showReadyState(player: Player) {
        const zoneMap = {
            'TopPlayer': 'TopZone',
            'RightPlayer': 'RightZone',
            'BottomPlayer': 'BottomZone',
            'LeftPlayer': 'LeftZone'
        };
    
        // 获取对应的出牌区节点
        const zoneName = zoneMap[player.node.name];
        const playZone = this.node.getChildByPath(`Player/CenterArea/PlayedCardZones/${zoneName}`);
        
        if (playZone) {
            const okNode = instantiate(this.okPrefab);
            // 设置适当的位置偏移（示例坐标）
            okNode.setPosition(0, 50, 0); 
            playZone.addChild(okNode);
            
            // 3秒后自动移除（可选）
            this.scheduleOnce(() => {
                okNode.destroy();
            }, 3);
        } else {
            console.error(`出牌区节点未找到: ${zoneName}`);
        }
    }

    private handleSpade7Owner() {
        const spade7 = this.allCards.find(c => c.value === 7 && c.suit === 1);
        const owner = this.players.find(p => 
            p.cards.some(c => c.value === spade7?.value && c.suit === spade7?.suit)
        );
    
        if (!owner) return;

        const countdownLabelPath = this.getCountdownPath(owner);
    const label = owner.node.getChildByPath(countdownLabelPath)?.getComponent(Label);
    if (label) {
        label.node.active = true; // 确保标签可见
    }

    
        if (owner.isBottomPlayer) {
            this.showTeamSelection(owner);
        } else {
            this.autoSelectTeamCard(owner);
        }
    }
    
    private showTeamSelection(player: Player) {
        // 获取可选2的列表
        const availableTwos = this.getAvailableTwos(player);
        
        // 显示选择按钮
        const buttonGroup = this.bottomPlayerNode.getChildByPath('ActionButtons');
        buttonGroup.removeAllChildren();
    
        availableTwos.forEach(two => {
            const btn = instantiate(this.teamSelectBtnPrefab);
            btn.getComponentInChildren(Label).string = two.displayName;
            btn.on(Node.EventType.TOUCH_END, () => this.onTeamSelected(two));
            buttonGroup.addChild(btn);
        });
    }
    
    private getAvailableTwos(player: Player): CardData[] {
        const twosInHand = player.cards.filter(c => c.value === 15);
        const allSuits = [1, 2, 3, 4];
        
        return allSuits
            .filter(suit => !twosInHand.some(c => c.suit === suit))
            .map(suit => new CardData(15, suit));
    }
    
    private onTeamSelected(selectedTwo: CardData) {
        // 更新队伍关系
        this.players.forEach(p => {
            const hasTeamCard = p.cards.some(c => 
                c.value === selectedTwo.value && 
                c.suit === selectedTwo.suit
            );
            
            const isTeam = p.isBottomPlayer ? false : hasTeamCard;
            this.updateTeamDisplay(p, isTeam);
        });
    }

    // 初始化中文名字
    private loadChineseNames(): string[] {
        // 示例名字列表（实际可扩展）
        return ["破军破军", "贪狼破军", "七杀破军", "天机天机", "太阴天机", 
                "天府天机", "武曲武曲", "太阳武曲", "廉贞武曲", "天相武曲"];
    }

    // 自动选择队伍卡
    private autoSelectTeamCard(owner: Player) {
        const availableTwos = this.getAvailableTwos(owner);
        const randomTwo = availableTwos[Math.floor(Math.random()*availableTwos.length)];
        this.onTeamSelected(randomTwo);
    }

    // 更新队伍显示
    private updateTeamDisplay(player: Player, isTeam: boolean) {
        const teamLabel = player.node.getChildByPath('UserInfo/IsTeam')?.getComponent(Label);
        if (teamLabel) {
            teamLabel.string = isTeam ? "队友" : "对手";
            teamLabel.node.active = false; // 初始隐藏
        }
    }

    // 自动出牌逻辑
    private autoPlayCards() {
        const currentPlayer = this.getCurrentPlayer();
        if (!currentPlayer.isBottomPlayer) {
            const playableCards = this.findPlayableCards(currentPlayer);
            if (playableCards.length > 0) {
                this.playCards(currentPlayer, playableCards);
            } else {
                this.passTurn(currentPlayer);
            }
        }
    }

    private getCurrentPlayer(): Player {
        // 实现回合管理逻辑
        return this.players[0]; // 示例返回
    }

    private findPlayableCards(player: Player): CardData[] {
        // 结合AI逻辑
        const ai = new AIManager();
        const result = ai.evaluateHand(player.cards);
        return result.bestCombination;
    }

    private playCards(player: Player, cards: CardData[]) {
        if (player.tryPlayCards(cards)) {
            // 成功出牌处理
            this.moveCardsToPlayZone(player, cards);
            this.passTurn(player);
        }
    }
    
    private passTurn(player: Player) {
        console.log(`${player.node.name} passes turn`);
        // 切换玩家逻辑
    }
    
    private moveCardsToPlayZone(player: Player, cards: CardData[]) {
        // 实现卡牌移动到出牌区的动画
        cards.forEach(card => {
            const cardNode = this.findCardNode(card);
            if (cardNode) {
                tween(cardNode)
                    .to(0.5, {
                        position: this.getPlayZonePosition(player),
                        scale: new Vec3(0.8, 0.8, 1)
                    })
                    .start();
            }
        });
    }

    private findCardNode(cardData: CardData): Node | null {
        // 遍历所有玩家手牌查找
        for (const player of this.players) {
            if (!player.handArea) continue;
            
            const cardNode = player.handArea.children.find(node => {
                const pc = node.getComponent(PokerCard);
                return pc?.data?.value === cardData.value && 
                       pc?.data?.suit === cardData.suit;
            });
            
            if (cardNode) return cardNode;
        }
        return null;
    }

    private getPlayZonePosition(player: Player): Vec3 {
        // 根据玩家位置获取对应出牌区坐标
        const zoneName = this.getZoneName(player);
        const zone = this.node.getChildByPath(`CenterArea/PlayedCardZones/${zoneName}`);
        return zone?.position.clone() || Vec3.ZERO;
    }
    
    private getZoneName(player: Player): string {
        switch (player.node.name) {
            case 'TopPlayer': return 'TopZone';
            case 'BottomPlayer': return 'BottomZone';
            case 'LeftPlayer': return 'LeftZone';
            case 'RightPlayer': return 'RightZone';
            default: return 'Center';
        }
    }

    // 单个玩家倒计时逻辑
    private startIndividualCountdown(player: Player) {
        const timerKey = `countdown_${player.node.uuid}`;
        
        // 清理旧定时器
        if (this.countdownTimers.has(timerKey)) {
            this.unschedule(this.countdownTimers.get(timerKey)!);
        }

        // 获取定时器ID（显式number类型）
        const timerId = this.schedule(() => {
            // 倒计时逻辑
        }, 1, 30);

        this.countdownTimers.set(timerKey, timerId);
    }

    // 获取正确的倒计时路径
    private getCountdownPath(player: Player): string {
        switch (player.node.name) {
            case 'TopPlayer':
                return 'CountdownBar/Label';
            case 'RightPlayer':
                return 'CountdownBar/Label';
            case 'BottomPlayer':
                return 'ActionButtons/CountdownBar/Label'; // 底部玩家特殊路径
            case 'LeftPlayer':
                return 'CountdownBar/Label';
            default:
                return 'CountdownBar/Label';
        }
    }

    // 更新倒计时显示（带视觉效果）
    private updateCountdownDisplay(player: Player, seconds: number) {
        const labelPath = this.getCountdownPath(player);
        const label = player.node.getChildByPath(labelPath)?.getComponent(Label);
        
        if (!label) return;

        // 更新文本
        label.string = `${seconds}s`;

        // 颜色变化逻辑
        const color = new Color();
        if (seconds > 10) {
            color.set(255, 255, 255); // 白色
        } else if (seconds > 5) {
            color.set(255, 165, 0);   // 橙色
        } else {
            color.set(255, 0, 0);     // 红色
        }

        // 缩放动画
        tween(label.node)
            .to(0.1, { scale: new Vec3(1.2, 1.2, 1) })
            .to(0.1, { scale: Vec3.ONE })
            .start();

        // 颜色渐变
        tween(label)
            .to(0.5, { color: color })
            .start();
    }

    // 超时处理
    private handleTimeout(player: Player) {
        console.log(`${player.node.name} 时间到`);
        
        if (player.isBottomPlayer) {
            // 玩家自动选择
            this.autoSelectForPlayer(player);
        } else {
            // AI自动出牌
            this.autoPlayForAI(player);
        }
    }

    // 玩家自动选择（底部玩家超时）
    private autoSelectForPlayer(player: Player) {
        if (!player.isBottomPlayer) return;

        // 示例：随机选择可用的2
        const availableTwos = this.getAvailableTwos(player);
        const randomTwo = availableTwos[Math.floor(Math.random() * availableTwos.length)];
        // this.processTeamSelection(randomTwo);
    
        console.log(`玩家自动选择: ${randomTwo.displayName}`);
    }

    // AI自动出牌（其他玩家超时）
    private autoPlayForAI(player: Player) {
        if (player.isBottomPlayer) return;

        // 示例：选择最小有效牌
        const playableCards = this.findPlayableCards(player);
        if (playableCards.length > 0) {
            this.playCards(player, playableCards);
        } else {
            this.passTurn(player);
        }
        console.log(`AI自动出牌: ${playableCards.map(c => c.displayName).join(',')}`);
    }

    
    protected onDestroy() {
        this.countdownTimers.forEach((timerId, key) => {
            this.unschedule(timerId);
        });
        this.countdownTimers.clear();
    }
}


